using UnityEngine;

namespace ZFramework.Runtime
{
    public abstract class UIFormLogic : MonoBehaviour
    {
        private bool _available = false;
        private bool _visible = false;
        private UIForm _uiForm = null;
        private Transform _cachedTransform;
        private int _originalLayer = 0;

        /// <summary>
        /// 获取已缓存的 Transform。
        /// </summary>
        public Transform CachedTransform
        {
            get { return _cachedTransform; }
        }

        public UIForm UiForm => _uiForm;

        public bool Visible
        {
            get { return _available && _visible; }
            set
            {
                if (!_available)
                {
                    Log.Warning("ui form is not available");
                    return;
                }

                if (_visible == value)
                    return;

                _visible = value;
                InternalSetVisible(value);
            }
        }

        public bool Available
        {
            get => _available;
        }

        public virtual void OnInit(object userData)
        {
            if (_cachedTransform == null)
                _cachedTransform = transform;

            _uiForm = GetComponent<UIForm>();
            _originalLayer = gameObject.layer;
        }

        public virtual void OnRecycle()
        {
        }

        public virtual void OnOpen(object userData)
        {
            _available = true;
            Visible = true;
        }

        public virtual void OnClose(object userData)
        {
            gameObject.SetLayerRecursively(_originalLayer);
            Visible = false;
            _available = false;
        }

        //暂停
        public virtual void OnPause()
        {
            Visible = false;
        }

        //暂停恢复
        public virtual void OnResume()
        {
            Visible = true;
        }

        //覆盖
        public virtual void OnCover()
        {
        }

        //覆盖恢复
        public virtual void OnReveal()
        {

        }

        //界面激活
        public virtual void OnRefocus(object userData)
        {
        }

        //轮询
        public virtual void OnUpdate(float elapseSeconds, float realElapseSeconds)
        {
        }

        //界面深度改变
        public virtual void OnDepthChanged(int uiGroupDepth, int depthInUIGroup)
        {

        }

        protected virtual void InternalSetVisible(bool visible)
        {
            gameObject.SetActive(visible);
        }
    }
}
